package com.gugee.ins.data.blogger.es.core;

import com.gugee.ins.common.dal.service.blogger.InsBloggerDao;
import com.gugee.ins.common.dal.service.media.InsMediaDao;
import com.gugee.ins.common.dal.service.media.InsRelMediaTaggerUserDao;
import com.gugee.ins.common.model.es.media.InsMediaIndex;
import com.gugee.ins.common.model.mysql.blogger.InsBlogger;
import com.gugee.ins.data.blogger.es.config.BloggerToElasticsearchAppConfig;
import com.xiguaji.boot.toolkit.elasticsearch.RestClientHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * 同步博主下的贴子到ES
 */
@Service
@Slf4j
public class MediaToEsService {

    @Autowired
    InsMediaDao insMediaDao;

    @Autowired
    InsBloggerDao insBloggerDao;

    @Autowired
    InsRelMediaTaggerUserDao insRelMediaTaggerUserDao;

    @Autowired
    BloggerToElasticsearchAppConfig bloggerToElasticsearchAppConfig;


    public void handler(List<Long> uIds){
        List<InsMediaIndex> insMediaIndices = new ArrayList<>();
        uIds.forEach( uid ->insMediaIndices.addAll(getMediaList(uid)));
        toEs(insMediaIndices);
    }

    public void handler(Long uid){
        List<Long> uIds = new ArrayList<>();
        uIds.add(uid);
        handler(uIds);
    }

    private List<InsMediaIndex> getMediaList(Long uid){
        // 时间区间
        long timeRang = System.currentTimeMillis() / 1000 - bloggerToElasticsearchAppConfig.getLatestDays() * 24 * 3600;
        List<InsMediaIndex> insMediaIndices = insMediaDao.findInsMediaIndexByOwnerUidAndTakenTime(uid,timeRang);
        InsBlogger insBlogger = insBloggerDao.findByUid(uid);

        insMediaIndices.forEach(insMediaIndex -> {
            insMediaIndex.setBloggerOverallCategoryName(insBlogger.getOverallCategoryName());
            // 提及博主
            insMediaIndex.setTaggedBloggers(insRelMediaTaggerUserDao.getInsMediaTaggedBloggerByShotCode(insMediaIndex.getShortcode()));
        });
        return insMediaIndices;
    }

    private void toEs(List<InsMediaIndex> insMediaIndices){
        if(insMediaIndices != null && insMediaIndices.size() > 0 ){
            RestClientHelper.upsert(bloggerToElasticsearchAppConfig.getMediaIndex(),insMediaIndices);
        }
    }
}
